<!--
 * @Date: 2023-03-09 15:18:59
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-11 10:19:26
 * @FilePath: \A19\frontend\src\components\Test\EditTest.vue
-->
<template>
  <div id="createTest" class="container">
    <div class="wrapper">
      <div class="left">
        <div class="header">
          <span>总题数:{{ qusInfo.len }} </span>
          &nbsp;
          <span>总分:{{ qusInfo.allScore }} </span>
        </div>
 
        <div v-for="kv,index in catedQuestions" :key="kv[0]">
          <div class="cate" v-show="kv[1].length !== 0">
            {{ kv[0] }} 
            <span class="de-btn" @click.stop="deleteCate(kv[0])">
              <el-icon><Delete /></el-icon>
            </span>
          </div>
          <div 
            class="quest" 
            @click="editQues(question)" 
            v-for="(question,index) in kv[1]" 
            :key="question._id"
            :style="{backgroundColor:currentQueID === question._id?'aliceblue':''}"
          >
            {{ index + 1 }}
            <span class="de-btn" @click.stop="deleteQuest(question._id)">
              <el-icon><Delete /></el-icon>
            </span>
          </div>
        </div>
        
      </div>
      <div class="right">
        <div class="controllers">
          <div class="text">添加题目</div>
          <!-- <CreateQuestion :course-id="courseId" :questions="questions"></CreateQuestion> -->
          <ElButton @click="createQues" type="primary">创建题目</ElButton>
          <QuestionsPanel :questions="questions"></QuestionsPanel>
          <ElButton style="margin-left: 50px;" @click="dialogVisible = true">提交</ElButton>
        </div>
        <div class="form">
          <div v-show="notEdit === 'none'" class="null">
            请选择编辑 或 添加题目
          </div>
          <div v-show="notEdit === 'new' || notEdit === 'edit'">
            <el-form
              ref="ruleFormRef"
              :model="questionForm"
              :label-width="60"
              :rules="rules"
            >
              <el-form-item label="题目" prop="question">
                <el-input v-model="questionForm.question.question" type="textarea" />
              </el-form-item>
              <ElFormItem label="类型" prop="type">
                <el-radio-group v-model="questionForm.question.type">
                  <el-radio label="选择题" />
                  <el-radio label="填空题" />
                  <el-radio label="简答题" />
                  <el-radio label="判断题" />
                </el-radio-group>
              </ElFormItem>
              <ElFormItem
                label="选项"
                prop="selections"
                v-if="['选择题', '判断题'].find((s) => s === questionForm.question.type)"
              >
                <div
                  class="input-item"
                  v-for="(selection, index) in questionForm.question.selections"
                  :key="index"
                >
                  <ElInput
                    ref="inputs"
                    @blur="inputBlur(index)"
                    style="margin-bottom: 18px"
                    v-model="questionForm.question.selections[index]"
                  ></ElInput>
                  <ElButton
                    text
                    icon="Minus"
                    type="danger"
                    @click="deleteSelection(index)"
                  ></ElButton>
                </div>
                <ElButton style="margin-left:0" icon="plus" @click="addSelection()"></ElButton>
              </ElFormItem>
              <ElFormItem label="分数">
                <el-input-number v-model="questionForm.question.score" :min="1" />
              </ElFormItem>
              <ElFormItem
                label="答案"
                prop="answer"
                v-if="
                  questionForm.question.type !== '简答题' &&
                  questionForm.question.type !== '填空题' &&
                  questionForm.question.type
                "
              >
                <el-checkbox-group
                  :min="1"
                  v-if="questionForm.question.type === '选择题'"
                  v-model="questionForm.answer.selections"
                >
                  <el-checkbox
                    :key="index"
                    v-for="(answer, index) in questionForm.question.selections"
                    :label="answer"
                    name="type"
                  />
                </el-checkbox-group>
                <ElRadioGroup
                  v-if="questionForm.question.type === '判断题'"
                  v-model="questionForm.answer.selection"
                >
                  <el-radio
                    :key="answer"
                    v-for="(answer, index) in questionForm.question.selections"
                    :label="answer"
                  />
                </ElRadioGroup>
              </ElFormItem>
              <ElFormItem
                label="填空数"
                prop="questionCount"
                v-if="questionForm.question.type === '填空题'"
              >
                <ElInputNumber
                  :min="1"
                  v-model="questionForm.question.questionCount"
                ></ElInputNumber>
              </ElFormItem>
            </el-form>
            <div class="foot">
              <div v-show="notEdit === 'new'">
                <el-button @click="clearForm" >重置</el-button>
                <el-button type="primary"  @click="confirm"> 创建题目 </el-button>
              </div>
              <div v-show="notEdit === 'edit'">
                <el-button @click="beforeEdit" >还原</el-button>
                <el-button type="primary"  @click="editEd"> 提交修改 </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>

  <el-dialog
    v-model="dialogVisible"
    title="提交"
    width="30%"
  >
  <el-form ref="commitFormRef" :rules="commitRule" :model="commitForm" label-width="80px">
    <el-form-item label="名称" prop="name">
      <el-input v-model="commitForm.name" />
    </el-form-item>
    <el-form-item label="开始时间" prop="time">
      <el-date-picker
        v-model="commitForm.date1"
        type="datetime"
        placeholder="Select date and time"
      />
    </el-form-item>
    <el-form-item label="结束时间" prop="time">
      <el-date-picker
        v-model="commitForm.date2"
        type="datetime"
        placeholder="Select date and time"
      />
    </el-form-item>
  </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelCreate">取消</el-button>
        <el-button type="primary" @click="save">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { useRoute } from 'vue-router';
import { useClientStore } from '../../pinia/stores/client';
import { questions } from '../../shared/types/Question';
import { createQuestionsHook } from '@/hooks/test/createQuestionsHook';
import { tests } from '../../shared/types/tests';
import { stringLiteral } from '@babel/types';
import { FormInstance, FormRules } from 'element-plus';

const store = useClientStore()
const {client} = store
const route = useRoute()
const examOrHomework = ref<'exam' | 'homework'>((route.name as 'editTest' | 'editHomework') === 'editTest'?'exam':'homework')
const currentTestId = route.params.testId as string

const notEdit = ref<'none' | 'new' | 'edit'>('none')
let loadingInstance:any

const questions = reactive(new Array<questions>)
const catedQuestions = computed(() =>{
  const qus = new Map<string,Array<questions>>()
  qus.set('选择题',new Array<questions>())
  qus.set('填空题',new Array<questions>())
  qus.set('简答题',new Array<questions>())
  qus.set('判断题',new Array<questions>())
  questions.forEach(question =>{
    qus.get(question.question.type)?.push(question)
  })

  return qus
})
const qusInfo = computed(()=>{
  const len = questions.length
  const allScore = questions.reduce((pre,cur,ar)=>{
    return pre + cur.question.score
  },0)
  return {
    len,
    allScore
  }
})

const {
  questionForm,
  rules,
  ruleFormRef,
  inputBlur,deleteSelection,addSelection,
  clearForm,confirm
} = createQuestionsHook({
  courseId:'',questions
})
const currentQueID = ref<string>('')
const editQues = (question:questions)=>{
  clearForm()
  notEdit.value = 'edit'
  questionForm.question = {
    ...question.question,
    selections:question.question.selections?question.question.selections:new Array<string>(),
    questionCount:question.question.questionCount?question.question.questionCount:1,
  }
  questionForm.answer = {
    selections: question.answer.selections?question.answer.selections:new Array<string>(),
    selection: question.answer.selection?question.answer.selection:'',
  };
  currentQueID.value = question._id
}
const beforeEdit = ()=>{
  const question = questions.find(q => q._id === currentQueID.value)
  if(!question) return
  questionForm.question = {
    ...question.question,
    selections:question.question.selections || new Array<string>(),
    questionCount:question.question.questionCount || 1
  }
  questionForm.answer = {
    selections: question.answer.selections || new Array<string>(),
    selection: question.answer.selection || '',
  };
}
const editEd = async ()=>{
  loadingInstance = ElLoading.service({
    target:'#createTest',
  })
  const question = questions.find(q => q._id === currentQueID.value)
  if(!question){
    ElMessage.error('题目不存在')
  }
  else{
    const ret = await client.callApi('QuestionsSys/EditQuestion',{
      _id:currentQueID.value,
      question:{
        ...questionForm.question,
              selections:
                questionForm.question.selections.length === 0
                  ? undefined
                  : questionForm.question.selections,
      },
      answer:{
        selection: questionForm.answer.selection || undefined,
            selections:
              questionForm.answer.selections.length === 0
                ? undefined
                : questionForm.answer.selections,
      }
    })
    if(ret.isSucc){
      question.answer = ret.res.question.answer
      question.question = ret.res.question.question
      ElMessage.success('修改成功')
    }
  }

  loadingInstance.close()
  currentQueID.value = ''
  clearForm()
  notEdit.value = 'none'
}
const createQues = ()=>{
  currentQueID.value = ''
  clearForm()
  notEdit.value = 'new'
}

const deleteQuest = (id:string)=>{
  if(id === currentQueID.value){
    clearForm()
    notEdit.value =  'none'
  }
  const index = questions.findIndex(q => q._id === id)
  if(index === -1) return

  questions.splice(index,1)
  ElMessage.success('移除成功')
}
const deleteCate = (cate:string) =>{
  let theC:string = cate
  // switch (cate) {
  //     case '判断题':
  //       theC = '判断题';
  //       break;
  //     case '简答题':
  //       theC = '简答题';
  //       break
  //     case '填空题':
  //       theC = '填空题';
  //       break
  //     case '选择题':
  //       theC = '选择题';
  //     default:
  //       break;
  //   }
  if(questions.find(q => q._id === currentQueID.value)?.question.type === cate){
    clearForm()
    notEdit.value =  'none'
  }
  
  const newQs = questions.filter(q => q.question.type !== theC)
  questions.length = 0
  questions.push(...newQs)
}

const dialogVisible = ref(false)
const commitFormRef = ref<FormInstance>()
const commitForm = reactive({
    _id:'',
    name:'',
    date1: new Date,
    date2: new Date,
})
const commitRule:FormRules = {
  name:{
    required:true,
    message:'请输入名称'
  }
}
const save = async ()=>{
    const ret = await client.callApi('QuestionsSys/SaveTest',{
        examOrHomework:examOrHomework.value,
        testId:commitForm._id,
        name:commitForm.name,
        startTime:commitForm.date1,
        endTime:commitForm.date2,
        questions:questions.map(q => q._id)
    })
    if(ret.isSucc){
        ElMessage.success('编辑成功')
        dialogVisible.value = false
    }
}
const cancelCreate = ()=>{
  dialogVisible.value = false
}

onMounted(async () =>{
  loadingInstance = ElLoading.service({
    target:'#createTest',
  })
  
  const ret = await store.client.callApi('Get/GetTestQuestions',{
    test:currentTestId,
    examOrHomework:examOrHomework.value
  })
  if(ret.isSucc){
      if(ret.res.test.length === 0){
      ElMessage.warning('不存在')
    }
    else{
      commitForm.name = ret.res.test[0].name
      commitForm._id = ret.res.test[0]._id
      commitForm.date1 = new Date(ret.res.test[0].startTime)
      commitForm.date2 = new Date(ret.res.test[0].endTime)
      
      questions.length = 0
      questions.push(...ret.res.test[0].questions as Array<questions>)
    }
  }
  loadingInstance.close()
})
</script>

<style lang="less" scoped>
@fontColor: #a6a6a6;
.container {
  height: 100%;
  width: 100%;
  background-color: #f2f4f7;
  padding: 5vh 0;
  overflow: auto;
  .wrapper {
    width: 80%;
    height: 90%;
    // background-color: aliceblue;
    position: relative;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;

    .left {
      width: 25%;
      height: 100%;
      background-color: white;
      border-radius: 10px;
      display: flex;
      flex-direction: column;
      overflow: auto;
      padding-top: 50px;
      &>div>div{
        .de-btn{
          float: right;
          font-size: 16px;
          display:none;
          line-height: 30px;
          color:#a6a6a6;
        }
      }
      &>div>div:hover{
        background-color: aliceblue;
        .de-btn{
          display: inline;
        }
      }
      .header{
        border-radius: 10px;
        height: 50px;
        color: #a6a6a6;
        font-size: 14px;
        text-align: left;
        line-height: 65px;
        padding: 0 20px;
        user-select: none;
        position: absolute;
        top: 0;
        left: 0;
        background: white;
      }
      .cate{
        height: 30px;
        color: black;
        font-size: 12px;
        font-weight: bold;
        line-height: 30px;
        padding: 0 20px;
        cursor: pointer;
      }
      .quest{
        height: 30px;
        color:@fontColor;
        font-size: 13px;
        line-height: 30px;
        padding: 0 20px;
        cursor: pointer;
      }
    }
    .right {
      width: 72%;
      height: 100%;
      // background-color: white;
      & > div {
        border-radius: 10px;
      }
      .controllers {
        height: 12%;
        width: 100%;
        background-color: white;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 0 30px;
        .text {
          color: @fontColor;
        }
        .el-button {
          margin-left: 20px;
        }
      }
      .form {
        position: relative;
        margin-top: 4%;
        // height: 80%;
        width: 100%;
        background-color: white;
        text-align: center;
        // line-height: 500px;
        color: @fontColor;
        padding:30px;
        .foot{
          padding-top:10px;
        }
      }
    }
  }
}

.input-item{
    width: 100%;
    display: flex;
}
</style>

<style lang="less">
.container {
  .el-button {
    margin-left: 20px;
  }
}
</style>